var express = require('express');
var router = express.Router();
let userService = require("../service/userinfoService");
let menuService = require("../service/userMenusService");
let typeService = require("../service/typesService");
let jwt = require("jsonwebtoken")

function generateRandomSixDigitNumber() {
  // Math.random() 生成一个 0 到 1 之间的随机小数
  // Math.floor() 用于向下取整
  // 通过调整数学表达式，生成 100000 到 999999 之间的随机数
  return Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000;
}

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

//登录
router.post('/login', async (req, res, next) => {
  let { telephone, password } = req.body;
  let isPwdWrong = await userService.query({ telephone, password })
  let isPhoneWrong = await userService.query({ telephone })
  console.log("isPwdWrong",isPwdWrong);
  
  //判断手机号存不存在
  if (!isPhoneWrong.length) {
    return res.json({
      code: 201,
      msg: "手机号不存在",
      data: telephone,
    });
  }
  //判断密码对不对
  if (isPwdWrong.length) {
    //token加密
    let token = jwt.sign({
      id: isPwdWrong[0]["_id"],
      telephone
    }, "abc", {
      expiresIn: 1000 * 30 * 60
    })

    res.json({
      code: "200",
      id: isPwdWrong[0]["_id"],
      token
    })
  } else {
    res.json({
      code: 203,
      msg: "用户名和密码不匹配",
    });
  }
});

//通过typeid查询用户
router.get('/list', async (req, res, next) => {
  let { typeid, pagenum, pagesize } = req.query
  let token = req.headers.token;
  //解密token
  jwt.verify(token, 'abc', async (err, info) => {
    if (!err) {
      let userid = info.id; //登录的用户的编号
      //查询到符合规则的数据
      let result = await userService.query({ typeid, pid: userid }, (pagenum - 1) * pagesize, pagesize * 1);
      //总数
      let total = await userService.total({ typeid, pid: userid });
      res.json({
        code: 200,
        msg: "查询成功",
        data: result,
        total
      })
    } else {
      res.json({
        code: 203,
        msg: "token过期或者已失效",
      })
    }
  })
});

//新增数据
// router.post("/add", async (req, res, next) => {
//   let { username, userpwd, typeid } = req.body;//post body  get query/params
//   let token = req.headers.token;
//   console.log(token);
//   jwt.verify(token, 'abc', async (err, info) => {
//     if (!err) {
//       let pid = info.id;
//       console.log(info);
//       let result = await userService.add({ username, userpwd, typeid, pid });
//       res.json({
//         code: 200,
//         data: result
//       })
//     } else {
//       res.json({
//         code: 203,
//         data: "token过期"
//       })
//     }
//   })
// })

//新增数据
router.post("/add", async (req, res, next) => {
  let { telephone, password, coupleId } = req.body;//post body  get query/params
  let iscoupleId = await userService.query({ coupleId })
  let isexist = await userService.query({ telephone })

  if (isexist.length) {
    return res.json({
      code: 201,
      msg: "手机号已存在",
      data: isexist.map((item) => item.telephone),
    });
  }

  if (!coupleId) {
    coupleId = generateRandomSixDigitNumber();
    let result = await userService.add({ telephone, password, coupleId });
    return res.json({
      code: 200,
      msg: "注册成功!",
      data: result
    })
  }

  if (iscoupleId.length >= 2) {
    return res.json({
      code: 201,
      msg: "该情侣已经绑定了情侣ID!",
      data: iscoupleId.map((item) => item.coupleId),
    });
  }

  if (coupleId && iscoupleId.length < 2) {
    let result = await userService.add({ telephone, password, coupleId });
    return res.json({
      code: 200,
      msg: "注册成功!",
      data: result
    })
  }
})


//通过模板批量新增数据
router.post("/addmany", async (req, res, next) => {
  let { list } = req.body;//post body  get query/params
  let token = req.headers.token;
  //结构token
  jwt.verify(token, 'abc', async (err, info) => {
    if (!err) {
      let usernameList = list.map(item => { item.username });
      let res2 = await userService.query({ username: { $in: usernameList } })

      //如果有重复的
      if (res2.length) {
        res.json({
          code: 201,
          msg: "有存在用户名",
          data: res2.map((item) => item.username),
        });
      } else {
        let pid = info.id;
        list = list.map((item) => {
          return {
            username: item.username,
            userpwd: "123456",
            typeid: 2,
            pid
          }
        })
        let result = await userService.addmany(list);
        res.json({
          code: 200,
          data: result
        })
      }
    } else {
      res.json({
        code: 203,
        data: "token过期"
      })
    }
  })
})

//删除数据
router.delete("/del", async (req, res, next) => {
  let _id = req.body;
  let result = await userService.del({ _id });
  res.json({
    code: 200,
    data: result
  })
})

//编辑数据
router.patch("/update", async (req, res, next) => {
  let { _id, username, userpwd } = req.body;
  let result = await userService.update({ _id }, { username, userpwd });
  res.json({
    code: 200,
    data: result
  })
})


module.exports = router;
